const XlsxPopulate = require('xlsx-populate');
const fs = require('fs');

async function generateExcelBuffer(data) {
    const workbook = await XlsxPopulate.fromBlankAsync();
    const sheet = workbook.sheet(0);
    // 填充数据
    for (let i = 0; i < data.length; i++) {
        const rowData = data[i];
        let j = 0;
        for (let m  in rowData) {
            const cellData = rowData[m];
            const cell = sheet.cell(i + 1, j + 1);
            
            cell.value(cellData);
            if(i == 0) {
                sheet.column(j + 1).width(sheet.cell(i + 1, j + 2).toString().length * 1.5);
                cell.style("fill", { type: "solid", color: "FFA500" });
            }
            j++;
        }
    }
    // 将工作簿保存为 Buffer 数据
    const bufferData = await workbook.outputAsync();
    return bufferData;
}

async function getExcelData(filePath) {
    XlsxPopulate.fromFileAsync(filePath).then(workbook => {
        const value = workbook.sheet("Sheet1").cell("A1").value();
 
        console.log(value);
    });
}

module.exports = {
    generateExcelBuffer,
    getExcelData
}